import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * for循环然后 操作双指针
 */
public class ThreeNumberAdd {
    public static void main(String[] args) {
      int[] sum = {-1,0,1,2,-1,-4};
        List<List<Integer>> lists = threeSum(sum);
        System.out.println(lists);
    }

    public static  List<List<Integer>> threeSum(int[] numbers){
        ArrayList<List<Integer>> result = new ArrayList<>();
        if(numbers ==null || numbers.length <= 2){
            return result;
        }
        int len = numbers.length;
        //有小到大进行排序
        Arrays.sort(numbers);
        for (int i = 0; i < (len - 2); i++) {
            if (i>0 && numbers[i] == numbers[i-1]){
                continue;
            }
            int left = i+1;
            int right =len - 1;
            while (left <right){
                if (numbers[i] +numbers[left] + numbers[right] ==0 ){
                    ArrayList<Integer> list = new ArrayList<>();
                    list.add(numbers[i]);
                    list.add(numbers[left]);
                    list.add(numbers[right]);
                    left++;
                    right--;
                    result.add(list);
                    while (left <right && numbers[left] == numbers[left-1]){
                        left++;
                    }
                    while (left <right && numbers[right] == numbers[right+1]){
                        right--;
                    }
                }else if (numbers[i]+numbers[left]+numbers[right] > 0){
                    right --;
                }else if (numbers[i]+numbers[left]+numbers[right] < 0){
                    left ++;
                }
            }
        }
      return result;
    }
}
